import { commonApi } from '@/common/api/commonApi.js'
import { bridge } from '@/common/plugin/utils/bridge'

const videoIframeRoutePath = '/base/play' // 前端播放视频 iframe 路由

/**
 * 安监系统视频相关
 */
export const video = {
  
  /**
   * 视频类型
   */
  videoTypeDic: [], 
  /**
   * 是否流地址？
   * @param { string } url 视频地址
   * @return { boolean }
   * 
   * 常见流媒体地址
   * RTMP rtmp://live.hkstv.hk.lxdns.com/live/hks(香港卫视)
   * RTSP rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov（大熊图点播）
   * HTTP http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8（CCTV 1高清）
   */
  isStreamAddress: async (url) => {
    let protocol = url.split(':')[0]
    if (protocol === 'rtmp' || protocol === 'rtsp') {
      return true
    } else if (protocol === 'http' || protocol === 'https') {
      let afterWord = url.substr(url.lastIndexOf('.'))
      if (afterWord === '.m3u8' || afterWord === '.flv') return true
    }
    return false
  },
  /**
   * 获取视频类型
   * @param { object } video
   * @return { object | null } videoType = { D_code:'', D_text: '' }
   */
  getType: async (video) => {
    if (!this.videoTypeDic.length) {
      try {
        this.videoTypeDic = await commonApi.dictionary('video_type')
      } catch (e) {
        return null
      }
    }
    return this.videoTypeDic.find(v => video.videoType === v.D_code || video.videoType === v.D_text)  
  },
  /**
   * 开始播放
   * @param { object } video = { videoType, AddressIP, DeviceNum } - 视频 
   * @return { promise }
   */
  play: (video) => {
    let self = this
    return new Promise((resolve, reject) => {

      let { videoType, AddressIP, DeviceNum } = video
      if (videoType === undefined && AddressIP === '' && DeviceNum === undefined) reject('错误的视频地址')

      videoType = videoType ? self.getType(videoType) : videoType

      let videoUrlAfter = AddressIP
      if (videoType) {
        if (videoType.D_text === '8700') {
          videoUrlAfter = DeviceNum
  
        } else if (videoType.D_text === '8200') {
          // TODO pc端尚未接入
          reject('暂不支持 8200 视频播放')
  
        } else if (videoType.D_text === '和目的') {
          videoUrlAfter = AddressIP
  
        } else if (videoType.D_text === '千里眼') {
          // TODO 移动平台暂不支持千里眼播放（约定所有千里眼视频都绑定到安监局下）
          reject('暂不支持 千里眼 视频播放')
  
        } else {
          reject('错误的视频地址')
        }
      }

      let isStream = this.isStreamAddress(videoUrlAfter)
      if (isStream) {
        bridge.Play(videoUrlAfter)
        resolve('流视频播放成功')
      } else {
        this.$router.$push({
          path: videoIframeRoutePath,
          query: { name: video.DeviceName, url: videoUrlAfter }
        })
        resolve('流视频播放成功')
      }
    })
    
  }
}
